<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="搜索" prop="no">
          <el-input
              v-model="queryParams.no"
              placeholder="请输入电池编号或型号"
              @keyup.enter="handleQuery()"
              style="width: 250px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search/>
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh/>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
            v-hasPerm="['system:sysDianciList:add']"
            type="success"
            @click="handleOpenDialog()"
        >
          <template #icon>
            <Plus/>
          </template>
          新增
        </el-button>
        <el-button
            v-hasPerm="['system:sysDianciList:delete']"
            type="danger"
            :disabled="removeIds.length === 0"
            @click="handleDelete()"
        >
          <template #icon>
            <Delete/>
          </template>
          删除
        </el-button>
      </div>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column
            key="createTime"
            label="创建时间"
            prop="createTime"
            min-width="200"
            align="center"
        />
        <el-table-column
            key="no"
            label="电池编号"
            prop="no"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="spec"
            label="电池型号"
            prop="spec"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="volume"
            label="容量"
            prop="volume"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="manufacturer"
            label="制造商"
            prop="manufacturer"
            min-width="250"
            align="center"
        />
        <el-table-column
            key="manufacturerDate"
            label="生产日期"
            prop="manufacturerDate"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="productionBatch"
            label="生产批次"
            prop="productionBatch"
            min-width="150"
            align="center"
        />
        <el-table-column label="状态" width="150" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.dianciState" code="dianciState"/>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
                v-hasPerm="['system:sysDianciList:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit/>
              </template>
              编辑
            </el-button>
            <el-button
                v-hasPerm="['system:sysDianciList:delete']"
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete/>
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <!-- 电池列表表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="500px"
        @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="电池编号" prop="no">
          <el-input
              v-model="formData.no"
              placeholder="电池编号"
              clearable
              show-word-limit
              maxlength="64"
          />
        </el-form-item>

        <el-form-item label="电池型号" prop="spec">
          <el-input
              v-model="formData.spec"
              placeholder="电池型号"
              clearable
              show-word-limit
              maxlength="64"
          />
        </el-form-item>

        <el-form-item label="容量" prop="volume">
          <el-input
              v-model="formData.volume"
              placeholder="容量"
              clearable
              show-word-limit
              maxlength="64"
          />
        </el-form-item>

        <el-form-item label="制造商" prop="manufacturer">
          <el-input
              v-model="formData.manufacturer"
              placeholder="制造商"
              clearable
              show-word-limit
              maxlength="64"
          />
        </el-form-item>

        <el-form-item label="生产日期" prop="manufacturerDate">
          <el-date-picker
              v-model="formData.manufacturerDate"
              type="date"
              placeholder="生产日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="生产批次" prop="productionBatch">
          <el-input
              v-model="formData.productionBatch"
              placeholder="生产批次"
              clearable
              show-word-limit
              maxlength="64"
          />
        </el-form-item>

        <el-form-item label="状态" prop="dianciState">
          <dict v-model="formData.dianciState" code="dianciState" style="width: 100%"/>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
              v-model="formData.remark"
              clearable
              type="textarea"
              placeholder="备注"
              show-word-limit
              maxlength="250"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "SysDianciList",
  inheritAttrs: false,
});

import SysDianciListAPI, {
  SysDianciListForm,
  SysDianciListPageQuery,
  SysDianciListPageVO
} from "@/api/system/sys-dianci-list";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<SysDianciListPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 电池列表表格数据
const pageData = ref<SysDianciListPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 电池列表表单数据
const formData = reactive<SysDianciListForm>({});

// 电池列表表单校验规则
const rules = reactive({
  no: [{required: true, message: "请输入电池编号", trigger: "blur"}],
  spec: [{required: true, message: "请输入电池型号", trigger: "blur"}],
  volume: [{required: true, message: "请输入容量", trigger: "blur"}],
  manufacturer: [{required: true, message: "请输入制造商", trigger: "blur"}],
  manufacturerDate: [{required: true, message: "请输入生产日期", trigger: "blur"}],
  productionBatch: [{required: true, message: "请输入生产批次", trigger: "blur"}],
  dianciState: [{required: true, message: "请输入状态", trigger: "blur"}],
});

/** 查询电池列表 */
function handleQuery() {
  loading.value = true;
  SysDianciListAPI.getPage(queryParams)
      .then((data) => {
        pageData.value = data.list;
        total.value = data.total;
      })
      .finally(() => {
        loading.value = false;
      });
}

/** 重置电池列表查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开电池列表弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改电池列表";
    SysDianciListAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增电池列表";
  }
}

/** 提交电池列表表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        SysDianciListAPI.update(id, formData)
            .then(() => {
              ElMessage.success("修改成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      } else {
        SysDianciListAPI.add(formData)
            .then(() => {
              ElMessage.success("新增成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭电池列表弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除电池列表 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
      () => {
        loading.value = true;
        SysDianciListAPI.deleteByIds(ids)
            .then(() => {
              ElMessage.success("删除成功");
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      },
      () => {
        ElMessage.info("已取消删除");
      }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
